#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Finder Tools 命令行界面
"""
import argparse
import sys
from pathlib import Path
from typing import List, Dict, Optional, Union, Any

from core import organizer, cleaner, batch, sync, converter

def format_size(size_bytes: int) -> str:
    """将字节数格式化为人类可读的大小"""
    if size_bytes < 1024:
        return f"{size_bytes} B"
    elif size_bytes < 1024 * 1024:
        return f"{size_bytes / 1024:.2f} KB"
    elif size_bytes < 1024 * 1024 * 1024:
        return f"{size_bytes / (1024 * 1024):.2f} MB"
    else:
        return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"

def organize_command(args: argparse.Namespace) -> None:
    """处理文件组织命令"""
    source_dir = Path(args.source_dir)
    target_dir = Path(args.target_dir) if args.target_dir else None
    
    # 检查源目录是否存在
    if not source_dir.exists() or not source_dir.is_dir():
        print(f"错误: 源目录 '{source_dir}' 不存在或不是一个目录")
        sys.exit(1)
    
    # 执行对应的组织功能
    if args.by_type:
        print(f"按文件类型整理目录: {source_dir}")
        stats = organizer.organize_by_type(source_dir, target_dir)
        print("\n整理结果:")
        for category, count in stats.items():
            if count > 0:
                print(f"  {category}: {count} 个文件")
        
    elif args.by_date:
        date_format = args.date_format or "年份/月份"
        use_modified = args.use_modified
        print(f"按{'修改' if use_modified else '创建'}日期整理目录: {source_dir}")
        print(f"使用日期格式: {date_format}")
        
        stats = organizer.organize_by_date(source_dir, target_dir, date_format, use_modified)
        print("\n整理结果:")
        for period, count in sorted(stats.items()):
            print(f"  {period}: {count} 个文件")
        
    elif args.by_size:
        print(f"按文件大小整理目录: {source_dir}")
        stats = organizer.organize_by_size(source_dir, target_dir)
        print("\n整理结果:")
        for category, count in stats.items():
            if count > 0:
                print(f"  {category}: {count} 个文件")
        
    elif args.by_regex:
        if not args.patterns:
            print("错误: 使用正则表达式整理时必须提供至少一个模式")
            sys.exit(1)
            
        # 解析正则表达式模式
        patterns = {}
        for pattern_str in args.patterns:
            if ":" not in pattern_str:
                print(f"错误: 模式格式不正确: {pattern_str}")
                print("正确格式: 类别名:正则表达式")
                sys.exit(1)
            
            category, regex = pattern_str.split(":", 1)
            patterns[category] = regex
        
        print(f"按正则表达式整理目录: {source_dir}")
        print("使用以下模式:")
        for category, pattern in patterns.items():
            print(f"  {category}: {pattern}")
            
        stats = organizer.organize_by_regex(source_dir, target_dir, patterns)
        print("\n整理结果:")
        for category, count in stats.items():
            if count > 0:
                print(f"  {category}: {count} 个文件")
    
    else:
        print("错误: 必须指定一种整理方式 (--by-type, --by-date, --by-size, 或 --by-regex)")
        sys.exit(1)

def clean_command(args: argparse.Namespace) -> None:
    """处理文件清理命令"""
    directory = Path(args.directory)
    
    # 检查目录是否存在
    if not directory.exists() or not directory.is_dir():
        print(f"错误: 目录 '{directory}' 不存在或不是一个目录")
        sys.exit(1)
    
    # 查找重复文件
    if args.duplicates:
        mode = "find" if args.find_only else "remove"
        keep = args.keep or "oldest"
        
        print(f"{'查找' if mode == 'find' else '删除'}重复文件于: {directory}")
        print(f"递归搜索: {'是' if args.recursive else '否'}")
        
        if mode == "remove":
            print(f"保留策略: {keep}")
        
        duplicates = cleaner.find_duplicates(directory, args.recursive)
        
        if not duplicates:
            print("未找到重复文件")
            return
            
        # 显示重复文件
        total_groups = len(duplicates)
        total_files = sum(len(files) - 1 for files in duplicates.values())
        total_size = sum(p.stat().st_size * (len(files) - 1) for hash_val, files in duplicates.items() for p in files)
        
        print(f"\n找到 {total_groups} 组重复文件，共 {total_files} 个可删除的文件（大小: {format_size(total_size)}）\n")
        
        if args.verbose:
            for hash_val, files in duplicates.items():
                print(f"重复组 (哈希值: {hash_val}):")
                file_size = files[0].stat().st_size
                for i, file_path in enumerate(files):
                    prefix = "  [保留]" if i == 0 and mode == "remove" else "  [删除]" if mode == "remove" else "  "
                    print(f"{prefix} {file_path} ({format_size(file_size)})")
                print()
        
        # 删除重复文件（如果需要）
        if mode == "remove" and not args.dry_run:
            deleted = cleaner.remove_duplicates(duplicates, keep)
            print(f"已删除 {sum(len(files) for files in deleted.values())} 个重复文件")
    
    # 查找/删除空文件夹
    elif args.empty_dirs:
        mode = "find" if args.find_only else "remove"
        
        print(f"{'查找' if mode == 'find' else '删除'}空文件夹于: {directory}")
        print(f"递归搜索: {'是' if args.recursive else '否'}")
        
        empty_dirs = cleaner.find_empty_dirs(directory, args.recursive)
        
        if not empty_dirs:
            print("未找到空文件夹")
            return
            
        print(f"\n找到 {len(empty_dirs)} 个空文件夹:")
        
        if args.verbose or len(empty_dirs) <= 10:
            for dir_path in empty_dirs:
                print(f"  {dir_path}")
        else:
            for dir_path in empty_dirs[:10]:
                print(f"  {dir_path}")
            print(f"  ... 以及 {len(empty_dirs) - 10} 个更多")
        
        # 删除空文件夹（如果需要）
        if mode == "remove" and not args.dry_run:
            deleted = cleaner.remove_empty_dirs(directory, args.recursive)
            print(f"已删除 {len(deleted)} 个空文件夹")
    
    # 查找/删除临时文件
    elif args.temp_files:
        mode = "find" if args.find_only else "remove"
        
        print(f"{'查找' if mode == 'find' else '删除'}临时文件于: {directory}")
        print(f"递归搜索: {'是' if args.recursive else '否'}")
        
        extensions = args.extensions.split(",") if args.extensions else None
        if extensions:
            print(f"使用自定义扩展名: {', '.join(extensions)}")
        
        temp_files = cleaner.find_temp_files(directory, args.recursive, extensions)
        
        if not temp_files:
            print("未找到临时文件")
            return
            
        total_size = sum(p.stat().st_size for p in temp_files)
        
        print(f"\n找到 {len(temp_files)} 个临时文件（大小: {format_size(total_size)}）:")
        
        if args.verbose or len(temp_files) <= 10:
            for file_path in temp_files:
                print(f"  {file_path} ({format_size(file_path.stat().st_size)})")
        else:
            for file_path in temp_files[:10]:
                print(f"  {file_path} ({format_size(file_path.stat().st_size)})")
            print(f"  ... 以及 {len(temp_files) - 10} 个更多")
        
        # 删除临时文件（如果需要）
        if mode == "remove" and not args.dry_run:
            deleted = cleaner.remove_temp_files(directory, args.recursive, extensions)
            print(f"已删除 {len(deleted)} 个临时文件")
    
    # 查找大文件
    elif args.large_files:
        min_size = args.min_size * 1024 * 1024  # 转换为字节
        
        print(f"查找大于 {args.min_size} MB 的文件于: {directory}")
        print(f"递归搜索: {'是' if args.recursive else '否'}")
        
        large_files = cleaner.find_large_files(directory, min_size, args.recursive)
        
        if not large_files:
            print(f"未找到大于 {args.min_size} MB 的文件")
            return
            
        total_size = sum(size for _, size in large_files)
        
        print(f"\n找到 {len(large_files)} 个大文件（总大小: {format_size(total_size)}）:")
        
        # 显示所有大文件，按大小排序
        limit = None if args.verbose else 20
        for i, (file_path, size) in enumerate(large_files):
            if limit is not None and i >= limit:
                print(f"  ... 以及 {len(large_files) - limit} 个更多")
                break
            print(f"  {file_path} ({format_size(size)})")
    
    else:
        print("错误: 必须指定一种清理方式 (--duplicates, --empty-dirs, --temp-files, 或 --large-files)")
        sys.exit(1)

def batch_command(args: argparse.Namespace) -> None:
    """处理批量操作命令"""
    directory = Path(args.directory)
    
    # 检查目录是否存在
    if not directory.exists() or not directory.is_dir():
        print(f"错误: 目录 '{directory}' 不存在或不是一个目录")
        sys.exit(1)
    
    # 批量重命名
    if args.rename:
        if not args.pattern or not args.replacement:
            print("错误: 重命名操作需要指定模式(--pattern)和替换文本(--replacement)")
            sys.exit(1)
            
        preview = args.preview
        recursive = args.recursive
        use_regex = args.regex
        
        print(f"{'预览' if preview else '执行'}批量重命名于: {directory}")
        print(f"模式: {args.pattern}")
        print(f"替换为: {args.replacement}")
        print(f"使用正则表达式: {'是' if use_regex else '否'}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        rename_map = batch.batch_rename(
            directory, args.pattern, args.replacement,
            use_regex=use_regex, recursive=recursive, preview=preview
        )
        
        if not rename_map:
            print("未找到匹配的文件进行重命名")
            return
        
        print(f"\n{'将重命名' if preview else '已重命名'} {len(rename_map)} 个文件:")
        
        for old_path, new_path in rename_map.items():
            print(f"  {old_path} -> {Path(new_path).name}")
    
    # 批量序列重命名
    elif args.sequence:
        if not args.pattern:
            print("错误: 序列重命名操作需要指定模式(--pattern)")
            sys.exit(1)
            
        preview = args.preview
        recursive = args.recursive
        start = args.start or 1
        padding = args.padding or 3
        
        print(f"{'预览' if preview else '执行'}批量序列重命名于: {directory}")
        print(f"模式: {args.pattern}")
        print(f"起始编号: {start}")
        print(f"数字填充长度: {padding}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        rename_map = batch.batch_rename_sequence(
            directory, args.pattern, start_number=start, 
            padding=padding, recursive=recursive, preview=preview
        )
        
        if not rename_map:
            print("未找到文件进行重命名")
            return
        
        print(f"\n{'将重命名' if preview else '已重命名'} {len(rename_map)} 个文件:")
        
        for old_path, new_path in rename_map.items():
            print(f"  {old_path} -> {Path(new_path).name}")
    
    # 批量压缩
    elif args.compress:
        pattern = args.file_pattern or "*"
        recursive = args.recursive
        format = args.format or "zip"
        individual = args.individual
        output_dir = args.output_dir
        
        print(f"批量压缩文件于: {directory}")
        print(f"文件模式: {pattern}")
        print(f"压缩格式: {format}")
        print(f"{'单独压缩每个文件' if individual else '压缩到单个文件'}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
            
        compression_map = batch.batch_compress(
            directory, pattern, recursive=recursive, 
            format=format, output_dir=output_dir,
            individual=individual
        )
        
        if not compression_map:
            print("未找到匹配的文件进行压缩")
            return
        
        print(f"\n已压缩 {len(compression_map)} 个{'文件' if individual else '组文件'}:")
        
        for source, target in compression_map.items():
            print(f"  {source} -> {target}")
    
    # 批量解压
    elif args.extract:
        pattern = args.file_pattern or "*.zip"
        output_dir = args.output_dir
        password = args.password
        
        print(f"批量解压文件于: {directory}")
        print(f"文件模式: {pattern}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
        if password:
            print("使用密码解压")
            
        extraction_map = batch.batch_extract(
            directory, pattern, output_dir=output_dir,
            password=password
        )
        
        if not extraction_map:
            print("未找到匹配的压缩文件进行解压")
            return
        
        print(f"\n已解压 {len(extraction_map)} 个文件:")
        
        for source, target in extraction_map.items():
            print(f"  {source} -> {target}")
    
    # 批量添加水印
    elif args.watermark:
        if not args.text:
            print("错误: 添加水印操作需要指定水印文本(--text)")
            sys.exit(1)
            
        try:
            from PIL import Image
        except ImportError:
            print("错误: 水印功能需要安装 Pillow 库")
            print("请运行: pip install Pillow")
            sys.exit(1)
            
        pattern = args.file_pattern or "*.jpg"
        recursive = args.recursive
        output_dir = args.output_dir
        position = args.position or "center"
        opacity = args.opacity or 0.5
        
        print(f"批量添加水印于: {directory}")
        print(f"水印文本: {args.text}")
        print(f"文件模式: {pattern}")
        print(f"水印位置: {position}")
        print(f"不透明度: {opacity}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
            
        watermark_map = batch.batch_watermark(
            directory, args.text, pattern=pattern, 
            recursive=recursive, output_dir=output_dir,
            position=position, opacity=opacity
        )
        
        if not watermark_map:
            print("未找到匹配的图片文件添加水印")
            return
        
        print(f"\n已处理 {len(watermark_map)} 个图片:")
        
        for source, target in watermark_map.items():
            print(f"  {source}")
    
    # 批量移除水印
    elif args.remove_watermark:
        try:
            from PIL import Image
        except ImportError:
            print("错误: 水印功能需要安装 Pillow 库")
            print("请运行: pip install Pillow")
            sys.exit(1)
            
        pattern = args.file_pattern or "*.jpg"
        recursive = args.recursive
        output_dir = args.output_dir
        tolerance = args.tolerance or 30
        
        print(f"批量移除水印于: {directory}")
        print(f"文件模式: {pattern}")
        print(f"颜色容差: {tolerance}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
            
        watermark_map = batch.batch_remove_watermark(
            directory, pattern=pattern, 
            recursive=recursive, output_dir=output_dir,
            tolerance=tolerance
        )
        
        if not watermark_map:
            print("未找到匹配的图片文件移除水印")
            return
        
        print(f"\n已处理 {len(watermark_map)} 个图片:")
        
        for source, target in watermark_map.items():
            print(f"  {source}")
    
    else:
        print("错误: 必须指定一个批量操作 (--rename, --sequence, --compress, --extract, --watermark, --remove-watermark)")
        sys.exit(1)

def sync_command(args: argparse.Namespace) -> None:
    """处理文件同步命令"""
    source_dir = Path(args.source_dir)
    target_dir = Path(args.target_dir)
    
    # 检查源目录是否存在
    if not source_dir.exists() or not source_dir.is_dir():
        print(f"错误: 源目录 '{source_dir}' 不存在或不是一个目录")
        sys.exit(1)
    
    # 执行对应的同步功能
    if args.one_way:
        mode = "one-way"
        preview = args.preview
        recursive = args.recursive
        delete = args.delete
        
        print(f"开始单向同步: {source_dir} -> {target_dir}")
        print(f"{'预览模式' if preview else '执行模式'}")
        print(f"递归处理: {'是' if recursive else '否'}")
        print(f"删除目标中多余文件: {'是' if delete else '否'}")
        
        changes = sync.sync_directories(
            source_dir, target_dir, 
            mode=mode, recursive=recursive, 
            delete=delete, preview=preview
        )
        
        if not changes:
            print("没有需要同步的变更")
            return
        
        # 显示变更
        if preview:
            print("\n预览同步操作:")
        else:
            print("\n已执行同步操作:")
        
        actions = {}
        for change in changes:
            action = change['action']
            if action not in actions:
                actions[action] = []
            actions[action].append(change['path'])
        
        for action, paths in actions.items():
            print(f"\n{action.upper()} 操作 ({len(paths)}):")
            for i, path in enumerate(paths):
                if i < 10 or preview:  # 在预览模式下显示所有，否则限制数量
                    print(f"  {path}")
                if i == 10 and not preview and len(paths) > 10:
                    print(f"  ... 以及 {len(paths) - 10} 个更多")
                    break
    
    elif args.two_way:
        mode = "two-way"
        preview = args.preview
        recursive = args.recursive
        conflict = args.conflict or "newer"
        
        print(f"开始双向同步: {source_dir} <-> {target_dir}")
        print(f"{'预览模式' if preview else '执行模式'}")
        print(f"递归处理: {'是' if recursive else '否'}")
        print(f"冲突处理策略: {conflict}")
        
        changes = sync.sync_directories(
            source_dir, target_dir, 
            mode=mode, recursive=recursive, 
            preview=preview, conflict_strategy=conflict
        )
        
        if not changes:
            print("没有需要同步的变更")
            return
        
        # 显示变更
        if preview:
            print("\n预览同步操作:")
        else:
            print("\n已执行同步操作:")
        
        actions = {}
        for change in changes:
            action = change['action']
            if action not in actions:
                actions[action] = []
            if 'resolution' in change:
                actions[action].append(f"{change['path']} ({change['resolution']})")
            else:
                actions[action].append(change['path'])
        
        for action, paths in actions.items():
            print(f"\n{action.upper()} 操作 ({len(paths)}):")
            for i, path in enumerate(paths):
                if i < 10 or preview:  # 在预览模式下显示所有，否则限制数量
                    print(f"  {path}")
                if i == 10 and not preview and len(paths) > 10:
                    print(f"  ... 以及 {len(paths) - 10} 个更多")
                    break
    
    elif args.backup:
        strategy = args.strategy or "timestamp"
        preview = args.preview
        recursive = args.recursive
        
        print(f"开始增量备份: {source_dir} -> {target_dir}")
        print(f"备份策略: {strategy}")
        print(f"{'预览模式' if preview else '执行模式'}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        changes = sync.backup(
            source_dir, target_dir, 
            strategy=strategy, recursive=recursive, 
            preview=preview
        )
        
        if not changes:
            print("没有需要备份的文件")
            return
        
        # 显示备份结果
        if preview:
            print(f"\n预览将备份 {len(changes)} 个文件:")
        else:
            print(f"\n已备份 {len(changes)} 个文件:")
        
        # 按原因分组显示
        reason_groups = {}
        for change in changes:
            reason = change.get('reason', '未知原因')
            if reason not in reason_groups:
                reason_groups[reason] = []
            reason_groups[reason].append(change['path'])
        
        for reason, paths in reason_groups.items():
            print(f"\n原因: {reason} ({len(paths)} 个文件)")
            for i, path in enumerate(paths):
                if i < 10 or preview:  # 在预览模式下显示所有，否则限制数量
                    print(f"  {path}")
                if i == 10 and not preview and len(paths) > 10:
                    print(f"  ... 以及 {len(paths) - 10} 个更多")
                    break
    
    elif args.scheduled:
        mode = "one-way" if args.one_way_scheduled else "two-way"
        interval = args.interval or 300  # 默认5分钟
        recursive = args.recursive
        delete = args.delete
        conflict = args.conflict or "newer"
        
        print(f"开始定时同步: {source_dir} {'-> ' if mode == 'one-way' else '<-> '}{target_dir}")
        print(f"同步间隔: {interval} 秒")
        print(f"同步模式: {mode}")
        print(f"递归处理: {'是' if recursive else '否'}")
        print(f"删除目标中多余文件: {'是' if delete else '否'}")
        if mode == "two-way":
            print(f"冲突处理策略: {conflict}")
        
        print("\n定时同步已启动，按Ctrl+C停止...")
        
        try:
            sync.scheduled_sync(
                source_dir, target_dir,
                interval=interval, mode=mode,
                recursive=recursive, delete=delete,
                conflict_strategy=conflict
            )
        except KeyboardInterrupt:
            print("\n定时同步已停止")
    
    else:
        print("错误: 必须指定一种同步模式 (--one-way, --two-way, --backup, --scheduled)")
        sys.exit(1)

def converter_command(args: argparse.Namespace) -> None:
    """处理文件格式转换命令"""
    directory = Path(args.directory)
    
    # 检查目录是否存在
    if not directory.exists() or not directory.is_dir():
        print(f"错误: 目录 '{directory}' 不存在或不是一个目录")
        sys.exit(1)
    
    # 图片格式转换
    if args.image:
        from_format = args.from_format
        to_format = args.to_format
        recursive = args.recursive
        output_dir = args.output_dir
        quality = args.quality or 90
        
        if not from_format or not to_format:
            print("错误: 图片转换需要指定源格式(--from-format)和目标格式(--to-format)")
            sys.exit(1)
        
        try:
            from PIL import Image
        except ImportError:
            print("错误: 图片转换功能需要安装 Pillow 库")
            print("请运行: pip install Pillow")
            sys.exit(1)
        
        print(f"批量转换图片格式于: {directory}")
        print(f"从 {from_format} 转换到 {to_format}")
        print(f"递归处理: {'是' if recursive else '否'}")
        print(f"图片质量: {quality}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
        
        try:
            converted_map = converter.batch_convert_images(
                directory, from_format, to_format,
                recursive=recursive, output_dir=output_dir,
                quality=quality
            )
            
            if not converted_map:
                print(f"未找到匹配的 {from_format} 格式图片进行转换")
                return
            
            print(f"\n已转换 {len(converted_map)} 个图片:")
            
            for source, target in converted_map.items():
                print(f"  {source} -> {target}")
        
        except ImportError as e:
            print(f"错误: {e}")
            sys.exit(1)
        except Exception as e:
            print(f"转换图片时出错: {e}")
            sys.exit(1)
    
    # 音频格式转换
    elif args.audio:
        from_format = args.from_format
        to_format = args.to_format
        recursive = args.recursive
        output_dir = args.output_dir
        bitrate = args.bitrate
        
        if not from_format or not to_format:
            print("错误: 音频转换需要指定源格式(--from-format)和目标格式(--to-format)")
            sys.exit(1)
        
        print(f"批量转换音频格式于: {directory}")
        print(f"从 {from_format} 转换到 {to_format}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        if bitrate:
            print(f"音频比特率: {bitrate}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
        
        try:
            if not converter.check_ffmpeg():
                print("错误: 音频转换功能需要安装 ffmpeg")
                print("请访问: https://ffmpeg.org/download.html")
                sys.exit(1)
            
            converted_map = converter.batch_convert_audio(
                directory, from_format, to_format,
                recursive=recursive, output_dir=output_dir,
                bitrate=bitrate
            )
            
            if not converted_map:
                print(f"未找到匹配的 {from_format} 格式音频进行转换")
                return
            
            print(f"\n已转换 {len(converted_map)} 个音频文件:")
            
            for source, target in converted_map.items():
                print(f"  {source} -> {target}")
        
        except EnvironmentError as e:
            print(f"错误: {e}")
            sys.exit(1)
        except Exception as e:
            print(f"转换音频时出错: {e}")
            sys.exit(1)
    
    # 视频格式转换
    elif args.video:
        from_format = args.from_format
        to_format = args.to_format
        recursive = args.recursive
        output_dir = args.output_dir
        video_bitrate = args.video_bitrate
        audio_bitrate = args.audio_bitrate
        resolution = args.resolution
        
        if not from_format or not to_format:
            print("错误: 视频转换需要指定源格式(--from-format)和目标格式(--to-format)")
            sys.exit(1)
        
        print(f"批量转换视频格式于: {directory}")
        print(f"从 {from_format} 转换到 {to_format}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        if video_bitrate:
            print(f"视频比特率: {video_bitrate}")
        if audio_bitrate:
            print(f"音频比特率: {audio_bitrate}")
        if resolution:
            print(f"分辨率: {resolution}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
        
        try:
            if not converter.check_ffmpeg():
                print("错误: 视频转换功能需要安装 ffmpeg")
                print("请访问: https://ffmpeg.org/download.html")
                sys.exit(1)
            
            converted_map = converter.batch_convert_video(
                directory, from_format, to_format,
                recursive=recursive, output_dir=output_dir,
                video_bitrate=video_bitrate,
                audio_bitrate=audio_bitrate,
                resolution=resolution
            )
            
            if not converted_map:
                print(f"未找到匹配的 {from_format} 格式视频进行转换")
                return
            
            print(f"\n已转换 {len(converted_map)} 个视频文件:")
            
            for source, target in converted_map.items():
                print(f"  {source} -> {target}")
        
        except EnvironmentError as e:
            print(f"错误: {e}")
            sys.exit(1)
        except Exception as e:
            print(f"转换视频时出错: {e}")
            sys.exit(1)
    
    # 文档格式转换
    elif args.document:
        from_format = args.from_format
        to_format = args.to_format
        recursive = args.recursive
        output_dir = args.output_dir
        
        if not from_format or not to_format:
            print("错误: 文档转换需要指定源格式(--from-format)和目标格式(--to-format)")
            sys.exit(1)
        
        print(f"批量转换文档格式于: {directory}")
        print(f"从 {from_format} 转换到 {to_format}")
        print(f"递归处理: {'是' if recursive else '否'}")
        
        if output_dir:
            print(f"输出目录: {output_dir}")
        
        try:
            converted_map = converter.batch_convert_documents(
                directory, from_format, to_format,
                recursive=recursive, output_dir=output_dir
            )
            
            if not converted_map:
                print(f"未找到匹配的 {from_format} 格式文档进行转换")
                return
            
            print(f"\n已转换 {len(converted_map)} 个文档文件:")
            
            for source, target in converted_map.items():
                print(f"  {source} -> {target}")
        
        except ImportError as e:
            print(f"错误: {e}")
            sys.exit(1)
        except Exception as e:
            print(f"转换文档时出错: {e}")
            sys.exit(1)
    
    else:
        print("错误: 必须指定一种转换类型 (--image, --audio, --video, 或 --document)")
        sys.exit(1)

def main() -> None:
    """主函数，处理命令行参数并执行相应的操作"""
    parser = argparse.ArgumentParser(description="Finder Tools - 文件夹自动化管理工具")
    
    # 添加GUI模式选项
    parser.add_argument("--gui", action="store_true", help="启动图形用户界面")
    parser.add_argument("--view-gui-structure", action="store_true", help="显示GUI结构而不实际运行GUI（不需要tkinter）")
    
    subparsers = parser.add_subparsers(dest="command", help="可用命令")
    
    # 组织文件命令
    organize_parser = subparsers.add_parser("organize", help="按规则整理文件")
    organize_parser.add_argument("source_dir", help="源目录路径")
    organize_parser.add_argument("--target-dir", help="目标目录路径（默认在源目录中创建子目录）")
    
    organize_group = organize_parser.add_mutually_exclusive_group()
    organize_group.add_argument("--by-type", action="store_true", help="按文件类型整理")
    organize_group.add_argument("--by-date", action="store_true", help="按日期整理")
    organize_group.add_argument("--by-size", action="store_true", help="按文件大小整理")
    organize_group.add_argument("--by-regex", action="store_true", help="按正则表达式整理")
    
    organize_parser.add_argument("--date-format", choices=["年份", "年份/月份", "年份/月份/日期"], 
                              help="日期格式（默认为'年份/月份'）")
    organize_parser.add_argument("--use-modified", action="store_true", help="使用修改日期（默认使用创建日期）")
    organize_parser.add_argument("--patterns", nargs="+", help="用于正则表达式整理的模式，格式为'类别:正则表达式'")
    
    # 清理文件命令
    clean_parser = subparsers.add_parser("clean", help="清理重复文件和空目录")
    clean_parser.add_argument("directory", help="目录路径")
    
    clean_group = clean_parser.add_mutually_exclusive_group(required=True)
    clean_group.add_argument("--duplicates", action="store_true", help="查找重复文件")
    clean_group.add_argument("--empty-dirs", action="store_true", help="查找空目录")
    clean_group.add_argument("--temp-files", action="store_true", help="查找临时文件")
    clean_group.add_argument("--large-files", action="store_true", help="查找大文件")
    
    clean_parser.add_argument("--recursive", action="store_true", help="递归处理子目录")
    clean_parser.add_argument("--find-only", action="store_true", help="仅查找不删除")
    clean_parser.add_argument("--verbose", action="store_true", help="显示详细信息")
    clean_parser.add_argument("--dry-run", action="store_true", help="模拟运行（不实际删除）")
    clean_parser.add_argument("--keep", choices=["oldest", "newest", "first"], help="保留策略（最旧、最新或第一个）")
    clean_parser.add_argument("--extensions", help="自定义临时文件扩展名（逗号分隔）")
    clean_parser.add_argument("--min-size", type=int, help="最小文件大小（MB）")
    
    # 批量操作命令
    batch_parser = subparsers.add_parser("batch", help="批量操作文件")
    batch_parser.add_argument("directory", help="目录路径")
    
    batch_group = batch_parser.add_mutually_exclusive_group(required=True)
    batch_group.add_argument("--rename", action="store_true", help="批量重命名文件")
    batch_group.add_argument("--sequence", action="store_true", help="按序列批量重命名文件")
    batch_group.add_argument("--compress", action="store_true", help="批量压缩文件")
    batch_group.add_argument("--extract", action="store_true", help="批量解压文件")
    batch_group.add_argument("--watermark", action="store_true", help="批量添加水印")
    batch_group.add_argument("--remove-watermark", action="store_true", help="批量移除水印")
    
    # 通用参数
    batch_parser.add_argument("--recursive", action="store_true", help="递归处理子目录")
    batch_parser.add_argument("--output-dir", help="输出目录路径")
    batch_parser.add_argument("--file-pattern", help="文件匹配模式")
    
    # 重命名相关参数
    batch_parser.add_argument("--pattern", help="要查找的模式或命名模式")
    batch_parser.add_argument("--replacement", help="替换文本")
    batch_parser.add_argument("--regex", action="store_true", help="使用正则表达式")
    batch_parser.add_argument("--preview", action="store_true", help="只预览不执行")
    batch_parser.add_argument("--start", type=int, help="序列起始编号")
    batch_parser.add_argument("--padding", type=int, help="序列数字填充长度")
    
    # 压缩相关参数
    batch_parser.add_argument("--format", choices=["zip", "tar", "gztar", "bztar", "xztar"], help="压缩格式")
    batch_parser.add_argument("--individual", action="store_true", help="单独压缩每个文件")
    batch_parser.add_argument("--password", help="压缩文件密码")
    
    # 水印相关参数
    batch_parser.add_argument("--text", help="水印文本")
    batch_parser.add_argument("--position", choices=["center", "top-left", "top-right", "bottom-left", "bottom-right"], 
                          help="水印位置")
    batch_parser.add_argument("--opacity", type=float, help="水印不透明度(0.0-1.0)")
    batch_parser.add_argument("--tolerance", type=int, help="移除水印的颜色容差")
    
    # 同步文件命令
    sync_parser = subparsers.add_parser("sync", help="同步或备份文件")
    sync_parser.add_argument("source_dir", help="源目录路径")
    sync_parser.add_argument("target_dir", help="目标目录路径")
    
    sync_group = sync_parser.add_mutually_exclusive_group(required=True)
    sync_group.add_argument("--one-way", action="store_true", help="单向同步（源到目标）")
    sync_group.add_argument("--two-way", action="store_true", help="双向同步（源和目标互相同步）")
    sync_group.add_argument("--backup", action="store_true", help="增量备份（源到目标）")
    sync_group.add_argument("--scheduled", action="store_true", help="定时同步")
    
    # 通用同步参数
    sync_parser.add_argument("--recursive", action="store_true", help="递归处理子目录")
    sync_parser.add_argument("--preview", action="store_true", help="只预览不执行")
    
    # 单向同步参数
    sync_parser.add_argument("--delete", action="store_true", help="删除目标中源没有的文件")
    
    # 双向同步参数
    sync_parser.add_argument("--conflict", choices=["newer", "older", "larger", "smaller", "source", "target"], 
                         help="冲突解决策略")
    
    # 备份参数
    sync_parser.add_argument("--strategy", choices=["timestamp", "hash", "size"], 
                         help="备份策略（时间戳、哈希值或大小比较）")
    
    # 定时同步参数
    sync_parser.add_argument("--interval", type=int, help="同步间隔（秒）")
    sync_parser.add_argument("--one-way-scheduled", action="store_true", 
                         help="使用单向模式（默认为定时双向同步）")
    
    # 格式转换命令
    convert_parser = subparsers.add_parser("convert", help="批量转换文件格式")
    convert_parser.add_argument("directory", help="目录路径")
    
    convert_group = convert_parser.add_mutually_exclusive_group(required=True)
    convert_group.add_argument("--image", action="store_true", help="转换图片格式")
    convert_group.add_argument("--audio", action="store_true", help="转换音频格式")
    convert_group.add_argument("--video", action="store_true", help="转换视频格式")
    convert_group.add_argument("--document", action="store_true", help="转换文档格式")
    
    # 通用转换参数
    convert_parser.add_argument("--from-format", help="源文件格式")
    convert_parser.add_argument("--to-format", help="目标文件格式")
    convert_parser.add_argument("--recursive", action="store_true", help="递归处理子目录")
    convert_parser.add_argument("--output-dir", help="输出目录路径")
    
    # 图片转换参数
    convert_parser.add_argument("--quality", type=int, help="图片质量(1-100)")
    
    # 音频转换参数
    convert_parser.add_argument("--bitrate", help="音频比特率(如'128k')")
    
    # 视频转换参数
    convert_parser.add_argument("--video-bitrate", help="视频比特率(如'1M')")
    convert_parser.add_argument("--audio-bitrate", help="音频比特率(如'128k')")
    convert_parser.add_argument("--resolution", help="视频分辨率(如'1280x720')")
    
    args = parser.parse_args()
    
    # 显示GUI结构
    if args.view_gui_structure:
        print("Finder Tools GUI 结构:")
        print("======================")
        print("\n1. 主窗口: FinderToolsApp")
        print("   - 菜单栏: 文件、帮助")
        print("   - 状态栏")
        print("   - 选项卡控件:")
        print("\n     a) 文件整理选项卡")
        print("        - 源目录选择")
        print("        - 目标目录选择（可选）")
        print("        - 整理类型选择：按文件类型、按日期、按文件大小、按正则表达式")
        print("        - 日期选项（使用日期格式选择、创建或修改日期）")
        print("        - 正则表达式选项")
        print("        - 执行按钮")
        print("        - 结果显示区域")
        
        print("\n     b) 文件清理选项卡")
        print("        - 目录选择")
        print("        - 清理类型选择：重复文件、空文件夹、临时文件、大文件")
        print("        - 基本选项：递归处理、仅查找不删除")
        print("        - 高级选项：保留策略、文件扩展名、最小文件大小")
        print("        - 执行按钮")
        print("        - 结果显示区域")
        
        print("\n     c) 批量操作选项卡")
        print("        - [开发中]")
        
        print("\n     d) 文件同步选项卡")
        print("        - [开发中]")
        
        print("\n     e) 格式转换选项卡")
        print("        - 源目录选择")
        print("        - 输出目录选择（可选）")
        print("        - 转换类型选择：图片、音频、视频、文档")
        print("        - 源格式和目标格式选择")
        print("        - 递归处理选项")
        print("        - 高级选项：质量、比特率、分辨率等")
        print("        - 执行按钮")
        print("        - 结果显示区域")
        
        print("\n提示: 要启动完整GUI，需安装tkinter库:")
        if sys.platform == "darwin":  # macOS
            print("  macOS: brew install python-tk")
        elif sys.platform.startswith("linux"):  # Linux
            print("  Linux (Debian/Ubuntu): sudo apt-get install python3-tk")
            print("  Linux (RHEL/CentOS): sudo yum install python3-tkinter")
        elif sys.platform == "win32":  # Windows
            print("  Windows: 大多数Python安装已包含tkinter，如有必要请重新安装Python并选中'tcl/tk'选项")
        return

    # 启动GUI
    if args.gui:
        try:
            # 检查是否可以导入tkinter
            try:
                import tkinter
            except ImportError:
                print("错误: 无法导入tkinter库")
                print("请确保您的Python安装包含tkinter支持")
                if sys.platform == "darwin":  # macOS
                    print("macOS用户可以尝试: brew install python-tk")
                elif sys.platform == "linux":  # Linux
                    print("Linux用户可以尝试: sudo apt-get install python3-tk 或 sudo yum install python3-tkinter")
                sys.exit(1)
                
            from gui.app import main as gui_main
            gui_main()
            return
        except Exception as e:
            print(f"无法启动图形界面: {e}")
            sys.exit(1)
    
    if args.command == "organize":
        organize_command(args)
    elif args.command == "clean":
        clean_command(args)
    elif args.command == "batch":
        batch_command(args)
    elif args.command == "sync":
        sync_command(args)
    elif args.command == "convert":
        converter_command(args)
    else:
        parser.print_help()

if __name__ == "__main__":
    main() 